"ui";
var color = "#009688";
ui.layout(
<vertical>
    <frame w="*" h="*">
        <webview id="webView" layout_below="title" />
    </frame>
</vertical>
);

let bridgeHandler  = require('bridgeHandler.js');
ui.webView.webViewClient = new JavaAdapter(android.webkit.WebViewClient, {
    onPageFinished: (webView, curUrl)=>{
        // 页面加载bridge
        let js = files.read("bridge.js");
        webView.loadUrl("javascript:" + js);
    },
    shouldInterceptRequest: (webView, request) => {
        try {
            let uris = request.a.a.split("/");
            if (uris[2] == "jsbridge") {
                let cmd = uris[3];
                let params = java.net.URLDecoder.decode(uris[4], "UTF-8");
                return handleJsBridge(cmd, params);
            }
        } catch (e) {
            console.log(e);
        }
    }
});
ui.webView.webChromeClient = new JavaAdapter(android.webkit.WebChromeClient, {
    onConsoleMessage: (msg) => {
        console.log("[%s:%s]: %s", msg.sourceId(), msg.lineNumber(), msg.message());
    }
});
/** 
 * JavaScript bridge 请求处理
 * @returns android.webkit.WebResourceResponse
 */
function handleJsBridge(cmd, params) {
    console.log('安卓接收到JavaScript调用请求: cmd=%s, params=%s', cmd, params);
    let data = {};
    try {
        data = bridgeHandler.handle(cmd, JSON.parse(params));
    } catch(e) {
        data = {message: e.message};
    }
    data = JSON.stringify(data || {});
    let bytes = new java.lang.String(data.toString()).getBytes();
    let response = new android.webkit.WebResourceResponse("application/json", "utf-8", new java.io.ByteArrayInputStream(bytes));
    let headers = new java.util.HashMap();
    // 设置允许跨域
    headers.put("Access-Control-Allow-Origin", "*");
    headers.put("Access-Control-Allow-Methods", "*");
    headers.put("Access-Control-Allow-Headers", "*");
    response.setResponseHeaders(headers);
    return response;
}

ui.webView.loadUrl("https://cn.bing.com/");
/**
 * 模拟JavaScript调用安卓
 * 两端统一好 cmd、params格式、callback的params 格式
 */ 
setTimeout(() => {
    ui.webView.loadUrl("javascript:window.Android.invoke('toast', {msg: '测试jsBridge1'}, (data) => {console.log('接收到callback1:' + JSON.stringify(data));});");
    ui.webView.loadUrl("javascript:window.Android.invoke('toast', {msg: '测试jsBridge2'}, (data) => {console.log('接收到callback2:' + JSON.stringify(data));});");
    ui.webView.loadUrl("javascript:window.Android.invoke('toast', {msg: '测试jsBridge3'}, (data) => {console.log('接收到callback3:' + JSON.stringify(data));});");
}, 2000);